var fechasClass = {
	parent: "parentId",
	pattern: "4H",
	win: null,
	form: null,
	grid: null,
    gridMun: null,
	actionBar: null,
    statusGrid:null,
    statusGridMun: null,
	layout: null,
	widgetWin: function(){
		var me = this,
            windows = new dhtmlXWindows();

		me.win = windows.createWindow('window_1', 0, 0, 900, 500);
        me.win.setText('Rango de Fechas para la Transcripción');
        me.win.setIcon('icon_09.png');
        me.win.button('park').hide();
        me.win.button('minmax1').hide();
        me.win.denyResize();
        me.win.setModal(1);
        me.win.centerOnScreen();

        widgetBar(me.win,1);
		me.layout = me.win.attachLayout('3W');
	},
	widgetBar: function(){		
		this.actionBar =  this.win.attachToolbar();
		this.actionBar.setIconsPath(mainPath+'resources/images/icons32/');
		this.actionBar.setIconSize(32);
		this.actionBar.loadXML(mainPath+"resources/xml/toolbar.xml");
		this.actionBar.setAlign('right');
	},
	widgetForm: function(){
		var me = this,
            str,
            panel = this.layout.cells('a');

		panel.setWidth('270');
		panel.setHeight('125');
		panel.hideHeader();
        panel.fixSize(true, true);

        str = [
			{ type:"settings" , labelWidth:80, inputWidth:250, position:"absolute"  },
			{ type:"select" , name:"tip_boleta", label:"Boleta:", labelAlign:"right", inputWidth:167, labelLeft:5, labelTop:15, inputLeft:88, inputTop:15,
                options: [{
                    text: "Ambas Boletas",
                    value: "ALL",
                    selected: true
                }, {
                    text: "Boleta de Infraestructura",
                    value: "BINF"
                }, {
                    text: "Boleta de Gestión",
                    value: "BGES"
                }]
            },
            { type: "hidden", name:"listMun"},
            { type:"calendar", name:"fecha_ini", dateFormat: "%d-%m-%Y", serverDateFormat: "%Y-%m-%d", label:"Fecha Inicio:", validate:"NotEmpty", readonly:true, labelAlign:"right", inputWidth:75, options:{}, labelLeft:5, labelTop:40, inputLeft:88, inputTop:40},
			{ type:"calendar", name:"fecha_fin", dateFormat: "%d-%m-%Y", serverDateFormat: "%Y-%m-%d", label:"Fecha Final:", validate:"NotEmpty", readonly:true, labelAlign:"right", inputWidth:75, options:{}, labelLeft:5, labelTop:65, inputLeft:88, inputTop:65},
			{ type:"button", name:"edit_btn", label:"Button", value:"Modificar", width:"75", inputWidth:75, inputLeft:100, inputTop:90  },
			{ type:"button", name:"save_btn", label:"Button", value:"Guardar", width:"75", inputWidth:75, inputLeft:180, inputTop:90  }
		];
		me.form = panel.attachForm(str);

        var dhxCalendar0 = me.form.getCalendar("fecha_ini");
        dhxCalendar0.loadUserLanguage("es");
        dhxCalendar0.hideTime();

        var dhxCalendar1 = me.form.getCalendar("fecha_fin");
        dhxCalendar1.loadUserLanguage("es");
        dhxCalendar1.hideTime();

        me.form.lock();
	},
    onEventForm: function(){
        var me = this;

        me.form.attachEvent("onButtonClick", function (name) {
            switch (name) {
                case 'save_btn':
                    me.onClickButtonSaveData();
                    break;
                case 'edit_btn':
                    me.onClickButtonEditData();
                    break;
            }
        });
    },
    onClickButtonSaveData: function(){
        var me = this,
            i,
            dataValChkd = Array(),
            dataChecked;

        if (me.form.validate()){
            if(me.gridMun.getCheckedRows(3) != ''){
                dataChecked = me.gridMun.getCheckedRows(3).split(',');
                for(i = 0; i<dataChecked.length; i++){
                    dataValChkd.push(me.gridMun.cells(dataChecked[i],0).getValue());
                }
                me.form.setItemValue('listMun',dataValChkd.join(','));
                me.form.send(mainPath + 'index.php/asignacion/save_data', function (loader, response) {
                    me.onLoadDataGrid();
                    me.form.clear();
                    me.form.lock();
                    actionBar.enableItem('btn_new');
                });
            }
            else
                dhtmlx.alert({
                    text:"Error, Tiene que seleccionar los Municipios."
                });
        }
        else
            dhtmlx.alert({
                text:"Error, Todos los campos de color rojo son necesarios."
            });
    },
    onClickButtonEditData: function(){
        var me = this,
            data,
            keyId,
            auxTxt;

        if(me.form.validate()){
            me.form.setItemValue('listMun',me.grid.cells(me.grid.getSelectedRowId(),1).getValue());
            me.form.send(mainPath + 'index.php/asignacion/edit_data', function (loader, response) {
                me.onLoadDataGrid();
                data = me.form.getFormData();
                keyId = me.grid.cells(me.grid.getSelectedRowId(),0).getValue();
                data.tip_boleta == 'BINF'?auxTxt = "Boleta de Infraestructura":auxTxt = "Boleta de Gestión";
                me.grid.cellByIndex(keyId-1,3).setValue(auxTxt);
                me.grid.cellByIndex(keyId-1,4).setValue(me.form.getCalendar("fecha_ini").getFormatedDate("%d-%m-%Y"));
                me.grid.cellByIndex(keyId-1,5).setValue(me.form.getCalendar("fecha_fin").getFormatedDate("%d-%m-%Y"));
                me.form.clear();
                me.form.lock();
            });
        }
        else
            dhtmlx.alert({
                text:"Error, Todos los campos de color rojo son necesarios."
            });
    },
    widgetGridMuni: function(){
        var me = this,
            cell = this.layout.cells('b');

        cell.hideHeader();
        cell.setWidth('240');
        me.statusGridMun = cell.attachStatusBar();

        me.gridMun = cell.attachGrid();
        me.gridMun.setImagePath(mainPath+'dhtmlx/imgs/');
        me.gridMun.setHeader("Id,Detalle,Departamento,");
        me.gridMun.attachHeader("&nbsp;,#combo_filter,&nbsp;,#master_checkbox");
        me.gridMun.setColTypes("ro,ro,ro,ch");
        me.gridMun.setColAlign("right,left,left,center");
        me.gridMun.setInitWidths("30,*,*,43");
        me.gridMun.setColumnHidden(2,true);
        me.gridMun.init();

        me.onLoadDataGridMuni();
    },
    onLoadDataGridMuni: function(){
        var me = this,
            ind,
            rowId;

        me.gridMun.load(mainPath+"index.php/municipio/gridAsigFechas", function(){
            me.gridMun.groupBy(2);
            me.statusGridMun.setText("Numero de Registros: "+me.gridMun.getRowsNum());
            me.onRemoveRowsGridMuni();
        },"json");
    },
    uniqueRows:function(ar){
        var ya=false,
            v="",
            i, a,
            aux=[].concat(ar),
            r=Array();

        for (i in aux){
            v=aux[i];
            ya=false;
            for (a in aux){
                if (v==aux[a]){
                    if (ya==false){
                        ya=true;
                    }
                    else{
                        aux[a]="";
                    }
                }
            }
        }
        for (a in aux){
            if (aux[a]!=""){
                r.push(aux[a]);
            }
        }
        return r;
    },
    onRemoveRowsGridMuni: function(){
        var me = this,
            i,
            ind,
            rows = Array(),
            rowsUnique = Array();

        me.grid.forEachRow(function(id){
            ind = me.grid.cells(id, 1).getValue();
            rows.push(ind);
        });
        rowsUnique = me.uniqueRows(rows);
        me.gridMun.forEachRow(function(id){
            var s = me.gridMun.cells(id, 0).getValue();
            for(i=0; i<rowsUnique.length; i++){
                if(s == rowsUnique[i]){
                    me.gridMun.deleteRow(id);
                }
            }
            me.statusGridMun.setText("Numero de Registros: "+me.gridMun.getRowsNum());
        });
    },
    widgetGrid: function(){
        var me = this,
            cell = this.layout.cells('c');

        cell.setWidth('330');
        cell.hideHeader();
        cell.fixSize(true, true);
        me.statusGrid = cell.attachStatusBar();

        me.grid = cell.attachGrid();
        me.grid.setImagePath(mainPath+'dhtmlx/imgs/');
        me.grid.setHeader("Id,CodMun,Municipio,Boleta,Fecha Ini.,Fecha Fin.");
        me.grid.attachHeader("&nbsp;,&nbsp;,#combo_filter,&nbsp;,&nbsp;,&nbsp;");
        me.grid.setColTypes("ro,ro,ro,ro,ro,ro");
        me.grid.setColAlign("right,left,left,left,center,center");
        me.grid.setInitWidths("30,*,170,*,*,*");
        me.grid.setColumnHidden(1, true);
        me.grid.setColumnHidden(3, true);
        me.grid.init();

        me.onLoadDataGrid();
    },
    onLoadDataGrid: function(){
        var me = this,
            ind;

        me.grid.load(mainPath+"index.php/asignacion/gridLoadData", function(){
            me.grid.groupBy(3);
            me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
            me.onRemoveRowsGridMuni();
        },"json");
    },
    onEventActionToolBar: function(){
        var me = this;

        actionBar.attachEvent("onClick", function(itemId){
            switch(itemId){
                case 'btn_new':
                    me.onClickButtonNew(itemId);
                    break;
                case 'btn_edit':
                    actionBar.enableItem('btn_new');
                    me.onClickButtonEdit();
                    break;
                case 'btn_erase':
                    me.onClickButtonErase();
                    break;
                case 'btn_clear':
                    me.onClickButtonClear();
                    break;
            }
        });
    },
    onClickButtonNew: function(itemId){
        var me = this;

        actionBar.disableItem(itemId);
        me.form.clear();
        me.form.unlock();
        me.form.disableItem('edit_btn');
        me.form.enableItem('save_btn');
    },
    onClickButtonEdit: function(){
        var me = this,
            comboVal,
            id = me.grid.getSelectedRowId();

        if(id != null){
            me.form.unlock();
            me.form.disableItem('save_btn');
            me.form.enableItem('edit_btn');

            switch(me.grid.cells(id,3).getValue()){
                case 'Boleta de Infraestructura':
                    comboVal = 'BINF';
                    break;
                default:
                    comboVal = 'BGES';
                    break;
            }
            me.form.setItemValue("tip_boleta", comboVal);
            me.form.setItemValue('fecha_ini', me.grid.cells(id,4).getValue().split('-').reverse().join('-'));
            me.form.setItemValue('fecha_fin', me.grid.cells(id,5).getValue().split('-').reverse().join('-'));
            me.form.disableItem('tip_boleta');
            //me.form.disableItem('fecha_ini');
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder editar."
            });
    },
    onClickButtonErase: function(){
        var me = this,
            rowId,
            comboVal;

        if(me.grid.getSelectedRowId() != null){
            rowId = me.grid.cells(me.grid.getSelectedRowId(),1).getValue();
            switch(me.grid.cells(me.grid.getSelectedRowId(),3).getValue()){
                case 'Boleta de Infraestructura':
                    comboVal = 'BINF';
                    break;
                default:
                    comboVal = 'BGES';
                    break;
            }
            dhtmlx.confirm({
                text:"¿Esta seguro que quieres eliminar el Ítem?",
                callback: function(status){
                    if(status == true){
                        me.form.send(mainPath+'index.php/asignacion/erase_data?id='+rowId+'&bol='+comboVal, function(loader, response){
                            if(response == true){
                                me.grid.deleteSelectedRows();
                                me.gridMun.clearAll();
                                me.onLoadDataGridMuni();
                                me.statusGrid.setText("Numero de Registros: "+me.grid.getRowsNum());
                            }
                            else
                                dhtmlx.alert({
                                    text: response
                                });
                        });
                    }
                }
            });
        }
        else
            dhtmlx.alert({
                text:"Error seleccione un Ítem para poder eliminar."
            });
    },
    onClickButtonClear: function(){
        var me = this;

        me.form.lock();
        me.form.clear();
        actionBar.enableItem('btn_new');
        me.grid.clearSelection();
        me.gridMun.clearSelection();
    },
	widgetMain: function(){
        var me = fechasClass;

		me.widgetWin();
        me.widgetForm();
        me.onEventForm();
        me.widgetGridMuni();
        me.widgetGrid();
        me.onEventActionToolBar();
	}
};